package com.xdth.sync.command;

import jodd.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by dy on 17-7-3.
 */
@Component("syncCommand")
public class SyncCommand {

    private static final Logger LOG = LoggerFactory.getLogger(RmtShellExecutor.class);

    @Value("#{config['oracle.home']}")
    private String oracleHome;

    @Value("#{config['log.home']}")
    private String logHome;

    @Value("#{config['sync.command']}")
    private String syncCommand;

    @Value("#{config['sync.ip']}")
    private String ip;
    @Value("#{config['sync.user']}")
    private String usr;
    @Value("#{config['sync.psword']}")
    private String psword;

    @Value("#{config['sync.data.dir']}")
    private String dataDir;

    public String getLogPath(String code) {
        return logHome + code + ".log";
    }

    public String getBadPath(String code) {
        return logHome + code + ".bad";
    }

    /**
     *
     * @param ctlFileName
     * @param dataFile
     * @return
     */
    public boolean exec(String ctlFileName, String dataFile) {
        if (StringUtil.isEmpty(oracleHome)) {
            oracleHome = "";
        }
        String command = syncCommand.replace("$ORACLE_HOME", oracleHome);
        String execLog = getLogPath(ctlFileName);
        String execBad = getBadPath(ctlFileName);
        command = command.replace("$logfile", execLog).replace("$badfile", execBad);
        command = command.replace("$filename", ctlFileName);
        command = command.replace("$datafile", dataDir+dataFile);
        RmtShellExecutor rmtShellExecutor = new RmtShellExecutor(ip, usr, psword);
        try {
            String result = rmtShellExecutor.exec(command);
            LOG.info("执行脚本完成:->{}",result);
            return Boolean.TRUE;
        } catch (IOException e) {
            LOG.error("执行脚本失败-->{}", command, e);
        } catch (InterruptedException e) {
            LOG.error("执行脚本失败-->{}", command, e);
        }
        return Boolean.FALSE;
    }


}